import { _decorator, Collider2D, Color } from 'cc';
import { Unit, UnitEvent } from './Unit';
import { UnitPlanetBase } from './UnitPlanetBase';
import { FactoryCom } from './Component/FactoryCom';
import GameEventMgr, { GameEvent } from '../Model/GameEventMgr';
import { Global, TechnologyType, UnitType } from '../Util/Global';
const { ccclass, property } = _decorator;


@ccclass('UnitPlanet')
export class UnitPlanet extends UnitPlanetBase {

    //单位 -- 被观察数量
    protected enemyList: Map<Unit, number> = new Map();
    get enemyCount() {
        return this.enemyList.size;
    }

    GetEnemyArr() {
        let arr = this.enemyList.keys();
        return Array.from(arr);
    }

    GetEnemyObservedFrequency(enemy: Unit) {
        return this.enemyList.get(enemy) || 0;
    }

    AddEnemy(enemy: Unit) {
        if (!enemy || !this.IsEnemy(enemy)) {
            return;
        }
        super.AddEnemy(enemy);
        if (enemy == null || enemy.parentUnit == this || enemy == this) {
            return;
        }
        // for(let i = 0; i < this.unit_children.length; i++){
        //     if(enemy == this.unit_children[i]){
        //         return;
        //     }
        // }

        let observedFrequency = this.enemyList.get(enemy) || 0;
        observedFrequency++;
        this.enemyList.set(enemy, observedFrequency);
        // if (observedFrequency == 1 && this == Global.gameManager.playerUnit) {
        //     console.log('发现敌人:', Tools.getEnumName(UnitType, enemy.unitType), enemy.uuid)
        // }

        enemy.on(this, UnitEvent.OnDestroy, () => {
            this.LostEnemy(enemy);
        })
    }

    LostEnemy(enemy: Unit) {
        if (!enemy || !this.IsEnemy(enemy)) {
            return;
        }
        super.LostEnemy(enemy);
        let observedFrequency = this.enemyList.get(enemy) || 0;

        observedFrequency -= 1;

        if (observedFrequency <= 0) {
            this.enemyList.delete(enemy);
            // if (this == Global.gameManager.playerUnit) {
            //     console.log('丢失敌人:', Tools.getEnumName(UnitType, enemy.unitType), enemy.uuid)
            // }
        }
        else {
            this.enemyList.set(enemy, observedFrequency);
        }
        // console.log('敌人:', Tools.getEnumName(UnitType, enemy.unitType), '丢失:', this.enemyList.get(enemy))
    }

    protected start() {
        super.start();
        this.unitType = UnitType.UnitPlanet;

        GameEventMgr.Register(this, GameEvent.EconomicComBroken, this.OnEnemyEconmicBroken.bind(this));
    }

    protected onEnable(): void {
        super.onEnable();

    }

    protected onDisable(): void {
        super.onDisable();
        this.enemyList.clear();
        this.SetBodyColor(Color.WHITE);
    }

    OnEnemyEconmicBroken(unit: Unit) {

        this.LostEnemy(unit);
    }

    FindEnemyNearest(): Unit {
        let tempDis = 0;

        let nearestUnit = null;
        let unValidUnits = [];
        for (let kv of this.enemyList) {
            if (!kv[0].death && this.IsEnemy(kv[0])) {
                let dis = this.DistanceOther(kv[0]);
                if (tempDis == 0 || dis < tempDis) {
                    tempDis = dis;
                    nearestUnit = kv[0];
                }
            }
            else {
                unValidUnits.push(kv[0]);
            }
        }

        for (let i = 0; i < unValidUnits.length; i++) {
            this.enemyList.delete(unValidUnits[i]);
        }

        return nearestUnit;
    }

    protected onTriggerEnter(selfCollider: Collider2D, otherCollider: Collider2D) {
        if (!this.isValid) {
            return;
        }
        // 只在两个碰撞体开始接触时被调用一次
        let other = otherCollider.node.getComponent(Unit);

        if (other) {
            if (other.unitType >= UnitType.UnitAsteroid) {
                let planet = (<UnitPlanetBase>other);

                if (other.unitType == UnitType.UnitAsteroid
                    && (!planet.forceTrackTarget
                        || planet.forceTrackTarget.unitType > this.unitType)) {
                    this.CheckPlanetOnTrank(planet);//先泊入轨道
                    planet.SetFixedTrackMoveTarget(this);
                    // planet.target = this;
                }
                planet.AddPlanetGravityImpact(this);
            }
            this.AddEnemy(other);
        }
    }

    protected onTriggerExit(selfCollider: Collider2D, otherCollider: Collider2D) {
        if (!this.isValid) {
            return;
        }
        let other = otherCollider.node.getComponent(Unit);

        if (other) {
            this.LostEnemy(other);

            if (other.unitType >= UnitType.UnitAsteroid) {
                let planet = (<UnitPlanetBase>other)

                planet.RemovePlanetGravityImpact(this);
            }
        }
    }

    IsEnemy(unit: Unit) {
        if (unit == null) {
            return false;
        }
        if (unit.unitType == UnitType.UnitPlanet) {

        }
        else if (!unit ||
            !(unit.unitType > UnitType.Bullet && unit.unitType <= UnitType.UnitSpacecra)) {
            return false;
        }
        if (unit.unitType == UnitType.UnitPlanet) {
            if (unit.getComponent(FactoryCom) == null) {
                return false;
            }
            else if (unit != this) {
                return true;
            }
        }
        if (unit
            && unit.parentUnit != this.parentUnit
            && unit != this.parentUnit
            && unit.parentUnit != this) {//对方和自己不来自一个父级
            return true;
        }
        return false;
    }
}


